<template>
    <div>
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card>
            <el-row>
                <el-col>
                    <el-button type="primary" @click="dialogRolesFormVisible = true">添加角色</el-button>
                </el-col>
            </el-row>

            <el-table :data="rolesList" border stripe>
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row :class="['bdbottom', index1 === 0 ? 'bdtop' : '','vcenter']" 
                            v-for="(item1,index1) in scope.row.children" :key="item1.id">
                            <el-col :span="5">
                                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <el-col :span="19">
                                <el-row :class="[index2 === 0 ? '' : 'bdtop','vcenter']" 
                                v-for="(item2,index2) in item1.children" :key="item2.id">
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag type="warning" closable @close="removeRightById(scope.row,item3.id)"
                                            v-for="(item3) in item2.children" :key="item3.id">{{item3.authName}}</el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column prop="roleName" label="角色名称"></el-table-column>
                <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
                <el-table-column label="操作" width="285px">
                    <template slot-scope="scoap">
                        <el-button type="primary" icon="el-icon-edit" size="mini" 
                            @click="showEditDialog(scoap.row)">编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" 
                            @click="deleteRole(scoap.row.id)">删除</el-button>
                        <el-button type="warning" icon="el-icon-setting" size="mini"
                            @click="showSetRightDialog(scoap.row)"
                            >分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <el-dialog title="分配权限" :visible.sync="dialogRightVisible" width="50%" @close="setRightDialogClosed()">
            <el-tree 
                :data="rightsList" 
                :props="treeProps" 
                show-checkbox 
                node-key="id"
                :default-expand-all="true"
                :default-checked-keys="defKeys"
                ref="treeRef"></el-tree>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogRightVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="添加角色" :visible.sync="dialogRolesFormVisible" width="30%" @close="addDialogClosed()">
            <el-form :model="addForm" :rules="addFormRoles" ref="addFormRef">
                <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="addForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="addForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogRolesFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRole()">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="修改角色" :visible.sync="dialogEditFormVisible" width="30%" @close="editDialogClosed()">
            <el-form :model="editForm" :rules="addFormRoles" ref="editFormRef">
                <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="editForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="editForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogEditFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="updateRole()">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data(){
        return{
            rolesList:[],
            dialogRightVisible: false,
            rightsList:[],
            treeProps:{
                children: 'children',
                label: 'authName'
            },
            defKeys:[],
            roleId:'',
            dialogRolesFormVisible: false,
            dialogEditFormVisible: false,
            addForm:{
                roleName:'',
                roleDesc:''
            },
            editForm: {
                roleId: '',
                roleName: '',
                roleDesc: ''
            },
            addFormRoles: {
                roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                ],
                roleDesc: [
                    { required: true, message: '请输入角色描述', trigger: 'blur' },
                ]
            }
        }
    },
    created(){
        this.getRolesList()
    },
    methods:{
        async getRolesList(){
            const {data: res} = await this.$http.get('roles')

            if(res.meta.status !== 200) return this.$message.error(res.meta.msg)

            this.rolesList = res.data
        },
        removeRightById(role,rightId){
            this.$confirm("确认删除吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
            .then(async () => {
                const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)

                if (res.meta.status !== 200) return this.$message.error('删除权限失败!')

                role.children = res.data
                
                return this.$message.success('删除权限成功!')
            })
            .catch(() => {});
        },
        async showSetRightDialog(role){
            this.roleId=role.id

            const {data: res} = await this.$http.get('rights/tree')

            if(res.meta.status !== 200) return this.$message.error(res.meta.msg)

            this.rightsList=res.data

            this.getLeafKeys(role,this.defKeys)

            this.dialogRightVisible = true
        },
        getLeafKeys(node,arr){
            if(!node.children){
                return arr.push(node.id)
            }

            node.children.forEach(item => {
                this.getLeafKeys(item,arr)
            });
        },
        setRightDialogClosed(){
            this.defKeys=[]
            this.roleId=''
        },
        async allotRights(){
            const keys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]

            const idStr = keys.join(',')

            const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})

            if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
            
            this.dialogRightVisible = false

            this.getRolesList()

            this.$message.success('分配权限成功!')
        },
        addDialogClosed(){
            this.$refs.addFormRef.resetFields()
        },
        addRole(){
            this.$refs.addFormRef.validate(async valid=>{
                if (!valid) return

                const { data: res } = await this.$http.post('roles', this.addForm)

                if (res.meta.status !== 201) return this.$message.error('添加角色失败!')

                this.dialogRolesFormVisible=false
                this.$refs.addFormRef.resetFields()

                this.getRolesList()
                this.$message.success('添加角色成功!')
            })
        },
        editDialogClosed(){
            this.$refs.editFormRef.resetFields()
        },
        async showEditDialog(roleInfo){
            const {data: res} = await this.$http.get(`roles/${roleInfo.id}`)

            if(res.meta.status !== 200) return this.$message.error('查询角色信息失败')

            this.editForm = res.data

            this.dialogEditFormVisible=true
        },
        updateRole(){
            this.$refs.editFormRef.validate(async valid=>{
                if (!valid) return

                const { data: res } = await this.$http.put(`roles/${this.editForm.roleId}`, this.editForm)

                if (res.meta.status !== 200) return this.$message.error('修改角色失败!')

                this.dialogEditFormVisible=false
                this.$refs.editFormRef.resetFields()

                this.getRolesList()
                this.$message.success('修改角色成功!')
            })
        },
        deleteRole(rId){
            this.$confirm("确认删除吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
            .then(async () => {
                const { data: res } = await this.$http.delete(`roles/${rId}`)

                if (res.meta.status !== 200) return this.$message.error('删除角色失败!')

                this.getRolesList()
                this.$message.success('删除角色成功!')
            })
            .catch(() => {});
        }
    }
}
</script>

<style lang="less" scoped>
    .el-tag{
        margin: 7px;
    }
    
    .bdtop{
        border-top:1px solid #eee;
    }

    .bdbottom{
        border-bottom: 1px solid #eee;

    }

    .vcenter{
        display: flex;
        align-items: center;
    }
</style>